package day04;

import com.blackhorse.domain.Account;
import com.blackhorse.domain.User;
import com.blackhorse.xml.dao.AccountMapper;
import com.blackhorse.xml.dao.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Demo1_LazyLoading {
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    private UserMapper userMapperr;
    private AccountMapper accountMapper;

    @Before
    public void init() {
        try {
            InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = builder.build(in);
            sqlSession = sqlSessionFactory.openSession();
            userMapperr = sqlSession.getMapper(UserMapper.class);
            accountMapper = sqlSession.getMapper(AccountMapper.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @After
    public void destory() {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

    //查询所有账户，同时一对一关联查询用户
    //使用延迟加载，需要在SqlMapConfig.xml中配置
    @Test
    public void testFindAllAccountWithUserByLazyLoading() {
        List<Account> accounts = accountMapper.findAllAccountWithUserByLazyLoading();
        for (Account account : accounts) {//如果不遍历accounts将不会执行查询用户的语句
            System.out.println("---------------------------------------------------");
            System.out.println(account);
            System.out.println(account.getUser());
        }
    }

    //查询所有用户，同时一对多关联查询账户
    //使用延迟加载，需要在SqlMapConfig.xml中配置
    @Test
    public void testFindAllUserWithAccountByLazyLoading() {
        List<User> users = userMapperr.findAllUserWithAccountByLazyLoading();
        for (User user : users) {//如果不遍历users将不会执行查询账户的语句
            System.out.println("-------------------------------------------------");
            System.out.println(user);
            for (Account account : user.getAccounts()) {
                System.out.println("\t" + account);
            }
        }
    }
}
